<template>
  <div class="login-container">
    <div class="login-card">
      <h2>客服登录</h2>

      <form @submit.prevent="handleLogin" class="login-form">
        <div class="form-group">
          <label>用户名</label>
          <input
              type="text"
              v-model="username"
              placeholder="请输入用户名"
              required
          >
        </div>

        <div class="form-group">
          <label>密码</label>
          <input
              type="password"
              v-model="password"
              placeholder="请输入密码"
              required
          >
        </div>

        <button type="submit" class="login-btn">登录</button>
      </form>

<!--      <button @click="$router.push('/')" class="back-btn">返回首页</button>-->
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';

const router = useRouter();
const store = useStore();

const username = ref('');
const password = ref('');

const handleLogin = () => {
  if (!username.value || !password.value) {
    alert('请输入用户名和密码');
    return;
  }

  // 调用后端登录接口
  const { $axios } = require('@/main').default.config.globalProperties;
  $axios.post('/admin/login', {
    username: username.value,
    password: password.value
  })
      .then(res => {
        const response = res.data;

        // 根据ResultDTO的code判断请求状态（0为成功）
        if (response.code === 0) {
          // 验证是否包含必要的admin数据
          if (response.data && response.data.admin && response.data.admin.id) {
            // 存储登录信息（与后端返回结构对应）
            store.dispatch('setAdminInfo', {
              adminId: response.data.admin.id,
              adminName: response.data.admin.name || response.data.admin.username
            });

            // 存储token到localStorage用于后续请求鉴权
            localStorage.setItem('token', response.data.token);

            // 跳转到后台首页
            router.push('/admin/dashboard');
          } else {
            alert('登录失败：未获取到管理员信息');
            console.warn('登录响应缺少admin数据', response);
          }
        } else {
          // 显示后端返回的错误信息
          alert(`登录失败：${response.message || '未知错误'}`);
        }
      })
      .catch(err => {
        console.error('登录请求异常', err);
        // 使用传统方式替代可选链操作符
        const errorMsg = err.message.includes('Network Error')
            ? '网络异常，请检查网络连接'
            : `登录失败：${(err.response && err.response.data && err.response.data.message) || '服务器错误'}`;
        alert(errorMsg);
      });
};
</script>

<style scoped>
/* 样式保持不变 */
.login-container {
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

.login-card h2 {
  text-align: center;
  color: #333;
  margin-bottom: 25px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-size: 14px;
  color: #666;
}

.form-group input {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
}

.form-group input:focus {
  outline: none;
  border-color: #165DFF;
}

.login-btn {
  padding: 12px;
  background-color: #165DFF;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.login-btn:hover {
  background-color: #0e47d1;
}

.back-btn {
  width: 100%;
  margin-top: 15px;
  padding: 10px;
  background: none;
  border: 1px solid #ddd;
  border-radius: 6px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  border-color: #165DFF;
  color: #165DFF;
}
</style>
